package com.lcx.plugin.neteaseCloud.component.toolwindow;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * @author daxiong
 * @date 2021/10/13 上午10:20
 */
public class CustomNodeRenderer extends DefaultListCellRenderer {

    private final Icon[] icons;
    private final Icon[] selectIcons;
    private int hoverIndex = -1;

    public CustomNodeRenderer(Icon[] icons, Icon[] selectIcons) {
        this.icons = icons;
        this.selectIcons = selectIcons;
    }

    @Override
    public Component getListCellRendererComponent(JList list, Object value, int index, boolean selected, boolean cellHasFocus) {
        super.getListCellRendererComponent(list, value, index, selected, cellHasFocus);
        this.setIcon(this.getIcon(index));
        this.setText(" " + value);

        if (selected) {
            setBackground(Color.BLUE);
            this.setIcon(this.getSelectIcon(index));
        } else {
            setBackground(index == hoverIndex ? Color.LIGHT_GRAY : Color.WHITE);
        }
        list.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                list.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
            }

            @Override
            public void mouseExited(MouseEvent e) {
                list.setCursor(Cursor.getDefaultCursor());
            }
        });
        list.addMouseMotionListener(new MouseAdapter() {
            @Override
            public void mouseMoved(MouseEvent e) {
                int index = list.locationToIndex(e.getPoint());
                setHoverIndex(list.getCellBounds(index, index).contains(e.getPoint()) ? index : -1);
            }

            private void setHoverIndex(int index) {
                if (hoverIndex == index) {
                    return;
                }
                hoverIndex = index;
                list.repaint();
            }
        });

        return this;
    }

    /**
     * 图标
     *
     * @param index 序号
     * @return
     */
    Icon getIcon(int index) {
        if (index >= 0 && icons.length > 0) {
            if (index < icons.length) {
                return icons[index];
            } else {
                return icons[0];
            }
        }
        return null;
    }

    /**
     * 图标
     *
     * @param index 序号
     * @return
     */
    Icon getSelectIcon(int index) {
        if (index >= 0 && selectIcons.length > 0) {
            if (index < selectIcons.length) {
                return selectIcons[index];
            } else {
                return selectIcons[0];
            }
        }
        return null;
    }
}